//引入QQMapWX核心类
import QQMapWX from "../../../libs/qqmap-wx-jssdk.min"
//导入async-validator进行表单验证
import Schema from "async-validator"
//导入接口api函数
import {
  reqAddAddress,
  reqAddressInfo,
  reqUpdateAddress
} from "../../../api/address"
Page({
  // 页面的初始数据
  data: {
    name: "", //收货人
    phone: "", //手机号
    provinceName: "", //省
    provinceCode: "", //省编码
    cityName: "", //市
    cityCode: "", //事编码
    districtName: "", //区
    districtCode: "", //区编码
    address: "", //详细地址
    fullAddress: "", //完整地址
    isDefault: false, //是否设置默认地址，0不设置为默认地址
  },

  // 保存收货地址
  async saveAddrssForm(event) {
    //组织参数(完整地址、是否设置默认地址)
    const {
      provinceName,
      cityName,
      districtName,
      address,
      isDefault
    } = this.data

    const params = {
      ...this.data,
      fullAddress: provinceName + cityName + districtName + address,
      isDefault: isDefault ? 1 : 0
    }
    //console.log(params)
    const {
      valid
    } = await this.validatorAddress(params)
    if (!valid) return
    if (valid) {
      // console.log(params)
      const res = this.addressId ? await reqUpdateAddress(params) : await reqAddAddress(params)
      //console.log(res)
      if (res.code == 200) {
        //返回到收获地址列表页面
        wx.navigateBack({
          success: () => {
            //需要给用户进行提示
            wx.toast({
              title: this.addressId ? "更新收获地址成功！" : "新增收获地址成功！"
            })
          }
        })
      }
    }
  },

  //对新增地址请求进行参数进行验证
  validatorAddress(params) {
    //验证收货人，是否包含大小写字母，数字和中文字符
    const nameRegExp = "^[a-zA-Z\\d\\u4e00-\\u9fa5]+$"
    //验证手机号，是否符合大陆手机号格式
    const phoneRegExp = "^1(?:3\\d|4[4-9]5[0-35-9]6[67]7[0-8]|8\\d|9\\d)\\d{8}$"

    //创建验证规则
    const rules = {
      name: [{
          required: true,
          message: "请输入收货人姓名"
        },
        {
          pattern: nameRegExp,
          message: "收货人姓名不合法"
        }
      ],
      phone: [{
          required: true,
          message: "请输入收货人手机号"
        },
        {
          pattern: phoneRegExp,
          message: "收货人手机号不合法"
        }
      ],
      provinceName: {
        required: true,
        message: "请选择收货人所在地区"
      },
      address: {
        required: true,
        message: "请输入详细地址"
      }
    }
    //传入验证规则进行实例化
    const validator = new Schema(rules)

    //调用实例方法对请求参数进行验证
    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          //如果验证失败，需要提示用户
          wx.toast({
            title: errors[0].message
          })
          resolve({
            valid: false
          })
        } else {
          resolve({
            valid: true
          })
        }
      })
    })
  },

  // 省市区选择
  onAddressChange(event) {
    console.log(event)
    //解构省市区
    const [provinceName,
      cityName,
      districtName
    ] = event.detail.value
    //解构省市区编码
    const [provinceCode,
      cityCode,
      districtCode
    ] = event.detail.code
    this.setData({
      provinceName,
      cityName,
      districtName,
      provinceCode,
      cityCode,
      districtCode
    })
  },

  //获取用户信息
  async onLoaction() {
    //获取当前的地理位置信息(精度、纬度、高度)
    // const res = await wx.getLocation()
    // console.log(res)
    const {
      latitude,
      longitude,
      name
    } = await wx.chooseLocation()

    //使用reverseGeocoder方法进行逆地址解析
    this.qqmapwx.reverseGeocoder({
      location: {
        latitude,
        longitude
      },
      success: (res) => {
        // console.log(res)
        //获取省市区，省市区编码
        const {
          adcode,
          province,
          city,
          district
        } = res.result.ad_info
        //获取街道，门牌
        const {
          street,
          street_number
        } = res.result.address_component

        //获取标准地址
        const {
          standard_address
        } = res.result.formatted_addresses

        //对获取的数据进行格式化、组织，然后赋值给data中的字段
        this.setData({
          provinceName: province,
          provinceCode: adcode.replace(adcode.substring(2, 6), "0000"),
          cityName: city,
          cityCode: adcode.replace(adcode.substring(5, 6), "00"),
          districtName: district,
          districtCode: district && adcode,
          address: street + street_number + name,
          fullAddress: standard_address + name
        })
      }
    })
  },


  //用来处理更新相关的逻辑
  async showAddressInfo(id) {
    //判断是否存在id
    if (!id) return
    //将id挂载到当前页面实例上，方便在多个方法上使用
    this.addressId = id

    //动态设置当前页面标题
    wx.setNavigationBarTitle({
      title: '更新收货地址',
    })
    const {
      data
    } = await reqAddressInfo(id)
    //将详情数据进行赋值
    this.setData(data)
  },
  onLoad(options) {
    //对核心类QQMapWX进行实例化
    this.qqmapwx = new QQMapWX({
      key: "P5DBZ-4DACZ-6Y7X2-7SGD4-M3ZIT-STF6O"
    })
    //调用方法实现更新
    this.showAddressInfo(options.id)
  },

})